<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="课程章节名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入课程章节名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入标题" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="课程" prop="courseId">
        <!-- <el-input v-model="queryParams.courseId" placeholder="请输入课程id" clearable @keyup.enter.native="handleQuery" /> -->
        <el-select v-model="queryParams.courseId" placeholder="请选择课程" style="width: 100%;">
          <el-option
            v-for="dict in courseList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          >
          </el-option>
        </el-select>


      </el-form-item>
      <el-form-item label="文件地址" prop="filePath">
        <el-input v-model="queryParams.filePath" placeholder="请输入文件地址" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="文件时长" prop="fileDuration">
        <el-input v-model="queryParams.fileDuration" placeholder="请输入文件时长" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="视频/音频" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择视频/音频" clearable>
          <el-option v-for="dict in dict.type.course_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input v-model="queryParams.sort" placeholder="请输入排序" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="章节数" prop="sections">
        <el-input v-model="queryParams.sections" placeholder="请输入章节数" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['yljf:course_package:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['yljf:course_package:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['yljf:course_package:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['yljf:course_package:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="course_packageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键id" align="center" prop="id" />
      <el-table-column label="课程章节名" width="160" align="center" prop="name">
        <template slot-scope="scope">
          <div class="cell-content">{{scope.row.name}}</div>
        </template>
      </el-table-column>
      <el-table-column label="标题" width="160" align="center" prop="title">
        <template slot-scope="scope">
          <div class="cell-content">{{scope.row.title}}</div>
        </template>
      </el-table-column>
<!--      <el-table-column label="课程id" align="center" prop="courseId" />-->
      <el-table-column label="文件地址" width="220" align="center" prop="filePath">
        <template slot-scope="scope">
          <el-link type="primary" :href="scope.row.filePath" target="_blank">{{scope.row.filePath}}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="文件时长" align="center" prop="fileDuration" >
        <template slot-scope="scope">
          {{secondsToMinsSecs(scope.row.fileDuration)}}
        </template>
      </el-table-column>
      <el-table-column label="视频/音频" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.course_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="章节数" align="center" prop="sections" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['yljf:course_package:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['yljf:course_package:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改课程目录对话框 -->
    <el-dialog :title="title"
      :visible.sync="open"
      width="560px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="modal-form">
        <el-form-item label="课程章节名" prop="name">
          <el-input v-model="form.name" placeholder="请输入课程章节名" />
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="课程" prop="courseId">
          <!-- <el-input v-model="form.courseId" placeholder="请输入课程id" /> -->

          <el-select @change="selectCourse" v-model="form.courseId" placeholder="请选择课程" style="width: 100%;">
            <el-option
              v-for="dict in courseList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            >
            </el-option>
          </el-select>
          <!-- </el-form-item> -->
        </el-form-item>


        <!-- <el-form-item label="视频/音频" prop="type">
          <el-select v-model="form.type" placeholder="请选择video/audio">
            <el-option
              v-for="dict in dict.type.course_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="音频|视频" prop="dibberId">

          <file-upload :limit="1" :isVideoOrAudio="true" @duration="setDuration" @dibberId="setDibberId"
            @delete="deleteVideo" :fileType="['mp4','avi','mov','mp3','wav','aac']" :fileSize="2048"
            v-model="form.dibberId" />


          <video :src="form.filePath" v-if="form.dibberId && form.type == 'video'" style="width: 100%;" controls></video>
          <audio :src="form.filePath" v-if="form.dibberId && form.type == 'audio'" style="width: 100%;" controls></audio>
        </el-form-item>



        <!-- <el-form-item label="章节数" prop="sections">
          <el-input v-model="form.sections" placeholder="请输入章节数" />
        </el-form-item> -->
        <el-form-item label="章节数" prop="sections">
          <!-- <el-input v-model="form.sections" disabled placeholder="请输入章节数" /> -->
          <el-select  @change="changeSort" v-model="form.sections" placeholder="请选择章节数" style="width: 100%;">
            <el-option
              v-for="section in sections"
              :key="section.id"
              :label="section.name"
              :value="section.id"
              >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" :disabled="true" placeholder="请输入排序" />
        </el-form-item>



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listCourse_package,
    getPlayInfo,
    getCourse_package,
    delCourse_package,
    addCourse_package,
    updateCourse_package
  } from "@/api/yljf/course_package";
  import {
    listCourse
  } from "@/api/yljf/course";
  export default {
    name: "Course_package",
    dicts: ['course_type'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 课程目录表格数据
        course_packageList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          name: null,
          title: null,
          courseId: null,
          filePath: null,
          fileDuration: null,
          type: null,
          sort: null,
          sections: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {},
        //章节列表
        sections: [
        {id:1,name:'一'},{id:2,name:'二'},{id:3,name:'三'},{id:4,name:'四'},{id:5,name:'五'},
        {id:6,name:'六'},{id:7,name:'七'},{id:8,name:'八'},{id:9,name:'九'},{id:10,name:'十'},
        ],
        courseList: [

        ]
      };
    },
    created() {
      this.getList();
      this.getListCourse()
    },
    methods: {
      // 根据更改排序信息
      changeSort(e){
        this.form.sort=e
        console.log(666);
      },
      /** 查询课程目录列表 */
      getList() {
        this.loading = true;
        listCourse_package(this.queryParams).then(response => {
          this.course_packageList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      secondsToMinsSecs(seconds) {
          let date = new Date(null);
          date.setSeconds(seconds); // 注意，这种方法会将秒数转换成毫秒
          let minutes = date.getMinutes();
          let secondsInMins = date.getSeconds();
          return `${minutes}:${secondsInMins.toString().padStart(2, '0')}`;
      },


      getListCourse() {
        listCourse({
          pageNum: 1,
          pageSize: 100,
        }).then(response => {
          console.log(response.rows.le)
          this.courseList = response.rows.map((item) => {
            return {
              value: item.id,
              label: item.name
            }
          })

          // this.courseList = this.courseList.concat(this.courseList,this.courseList)
        });
      },


      numberToChinese(num) {
          if (num > 1000) {
              throw new Error('数字超过1000，无法转换');
          }

          const chineseNums = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
          const units = ['', '十', '百'];

          let result = '';
          let unitIndex = 0; // 用于记录单位（十位、百位）的索引

          while (num > 0) {
              const digit = num % 10; // 获取当前最低位的数字
              if (digit !== 0 || unitIndex === 0) { // 如果数字不为零或者是个位，直接添加数字和单位
                  result = chineseNums[digit] + units[unitIndex] + result;
              } else if (digit === 0 && unitIndex !== 0) { // 如果数字为零且不是个位，只添加'零'
                  result = chineseNums[digit] + result;
              }
              num = Math.floor(num / 10); // 移除已处理的最低位
              unitIndex++; // 移动到下一个单位（十位、百位）
          }

          // 处理连续的'零'的情况，例如101转换为“一百零一”而不是“一百一”
          result = result.replace(/零+/g, '零');
          // 处理开头的'零'和末尾的'零'
          result = result.replace(/^零|零$/g, '');

          return result;
      },

      // 首先，我们需要一个函数来将中文数字转换为阿拉伯数字
      chineseToNumber(str) {
          const chineseNumbers = {
              '九': 9, '八': 8, '七': 7, '六': 6, '五': 5,
              '四': 4, '三': 3, '二': 2, '一': 1, '十': 10,
              '百': 100, '千': 1000, '万': 10000 // 可以根据需要扩展
          };
          let result = 0;
          let temp = 1; // 用于记录当前的数值单位，如个、十、百等
          for (let i = str.length - 1; i >= 0; i--) {
              const num = chineseNumbers[str[i]];
              if (num >= 10) { // 如果是单位，如十、百等
                  temp = num;
              } else { // 如果是数字，则乘以对应的单位
                  result += num * temp;
                  temp = 1; // 重置单位为个位
              }
          }
          return result;
      },


      selectCourse(courseId){
        console.log(courseId)
        listCourse_package({
          pageNum: 1,
          pageSize: 100,
          courseId
        }).then(response => {
          console.log(response);

          // console.log(response.rows.length)
          // console.log()
          if(response.rows.length > 0){
            var numbers = response.rows.map(item=>{
              return item.sections
            })

            let numberArray = numbers.map(this.chineseToNumber)
            let maxNumber = Math.max(...numberArray)
            this.form.sections = ''
            this.sections = this.getMissingNumbersWithChinese(numberArray)
          } else {

            this.form.sections = ''
            this.sections = ['一','二','三']

          }


          // console.log(maxNumber,numberArray,a)
          // this.form.sections = this.numberToChinese(response.rows.length + 1)

        });

      },

      getMissingNumbersWithChinese(arr) {
          const max = Math.max(...arr);
          const maxPlusOne = max + 3;
          const allNumbers = Array.from({ length: maxPlusOne }, (_, i) => i + 1);
          const originalSet = new Set(arr);
          const missingNumbers = allNumbers.filter(n => !originalSet.has(n));

          const units = ['', '一', '二', '三', '四', '五', '六', '七', '八', '九'];

          function numberToChinese(n) {
              let result = '';
              const hundred = Math.floor(n / 100);
              if (hundred > 0) {
                  result += units[hundred] + '百';
              }

              const ten = Math.floor((n % 100) / 10);
              const one = n % 10;

              if (ten > 0 || one > 0) {
                  if (hundred > 0 && ten === 0 && one !== 0) {
                      result += '零';
                  }

                  if (ten > 0) {
                      if (hundred === 0 && ten === 1) {
                          result += '十';
                      } else {
                          result += units[ten] + '十';
                      }
                  }

                  if (one > 0) {
                      result += units[one];
                  }
              }

              return result;
          }

          return missingNumbers.map(numberToChinese);
      },




      setDuration(result) {
        console.log('setDuration', result)
        this.form.fileDuration = result.duration;
        this.form.type = result.type
        // console.log('setDuration',this.form.dibber_id)
      },

      setDibberId(dibberId) {
        console.log('setDibberId', dibberId, this.form)
        getPlayInfo({
          videoId: dibberId
        }).then(response => {
          console.log(response.data)
          if (response.code == 200) {
            this.form.filePath = response.data.filePath
            this.form.imgUrl = response.data.imgUrl
            console.log(this.form)
          }


        });

      },
      deleteVideo() {
        this.form.filePath = null;
        this.form.imgUrl = null;
        this.form.fileDuration = null;
        this.form.type = null
      },


      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          name: null,
          title: null,
          courseId: null,
          filePath: null,
          fileDuration: null,
          type: null,
          createTime: null,
          sort: null,
          sections: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加课程目录";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getCourse_package(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改课程目录";

          this.selectCourse(row.courseId)
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateCourse_package(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addCourse_package(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除课程目录编号为"' + ids + '"的数据项？').then(function() {
          return delCourse_package(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('yljf/course_package/export', {
          ...this.queryParams
        }, `course_package_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
<style lang="scss" scoped>
  .cell-content {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3;
    /* 限制行数为3 */
    overflow: hidden;
  }

  ::v-deep {
    .el-form-item__label {
      width: initial !important;
    }
  }


  .modal-form{
    max-height: 450px;
    overflow-y: auto;
    padding-right: 20px;

  }

  .modal-form::-webkit-scrollbar {
      width: 5px;
      // height: 12px;
  }
  .modal-form::-webkit-scrollbar-track {
      background: #f1f1f1;
      // border-radius: 5px;
  }

  .modal-form::-webkit-scrollbar-thumb {
      background: #888;
      border-radius: 10px;
  }
</style>
